package com.sgb.kjwl.view.ui.fragment.transport;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.google.android.material.tabs.TabLayout;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentMapCarrierBinding;
import com.sgb.kjwl.di.transport.DaggerTransportFragComponent;
import com.sgb.kjwl.di.transport.TransportFragModule;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.GoodsSourceLocationEntity;
import com.sgb.kjwl.model.entity.transport.MapCarEntity;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.utils.TextViewUtils;
import com.sgb.kjwl.view.ui.adapter.transport.LogisticsFilterTabAdapter;
import com.sgb.kjwl.view.widget.CarMapInfoWindow;
import com.sgb.kjwl.view.widget.GoodsTypePopWindow3;
import com.sgb.kjwl.view.widget.MapCarPopWindow;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.viewmodel.transport.MapCarrierFramgentModel;
import com.sgb.kjwl.viewmodel.transport.MapCarsFramgentModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PermissionUtils;
import com.swgk.core.util.ScreenUtil;
import com.swgk.core.util.SharedPreferenceUtil;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * @author: 王彬臣
 * @date:
 * @Description: 竞价找车地图
 */
public class MapCarrierFragment extends AppLazyFragment implements
        TabLayout.OnTabSelectedListener, AMap.OnMarkerClickListener,
        AMap.OnCameraChangeListener {
    @Inject
    MapCarrierFramgentModel viewModel;
    FragmentMapCarrierBinding binding;
    //
    private Activity _mActivity;
    //地图控制器
    private AMap aMap;
    //当前定位位置信息
    private LatLng mCurLatLng;
    //地图缩放比例
    private float mZoom = 11;
    //最小缩放级别（全国）
    private final float mMinZoom = 3;
    //全国中心点经纬度
    private final LatLng mCenterLatLng = new LatLng(35.03349, 103.03319);
    //页面弹窗
    private GoodsTypePopWindow3 mLenPop;//车长
    private GoodsTypePopWindow3 mTypePop;//车辆类型
    private ThreeLevelAreaWindow mSendPop;//车辆发货地
    private ThreeLevelAreaWindow mDestPop;//车辆目的地
    private MapCarPopWindow mMapCarPop;//地图车辆弹窗
    //marker集合
    private final List<Marker> mMarkers = new ArrayList<>();
    //当前最后一个点击的marker
    private Marker mLastMarker;
    //屏幕高度
    private int mScreenHeight;
    //是否需要移动地图加载数据
    private boolean mIsNeedLoadByCamera;
    private boolean currentIsSearching = false;

    public static MapCarrierFragment newInstance() {
        return new MapCarrierFragment();
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerTransportFragComponent.builder()
                .appComponent(appComponent)
                .transportFragModule(new TransportFragModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        _mActivity = (Activity) context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_map_carrier, container, false);
        binding.setLifecycleOwner(this);
        binding.mapFindCarByMap.onCreate(savedInstanceState);
        return binding.getRoot();
    }

    @Override
    protected void onLazyLoad() {
        initMap();
        initPopup();
        initEvent();
        initData();
    }

    /**
     * 初始化地图
     */
    private void initMap() {
        //获取地图控制类
        aMap = binding.mapFindCarByMap.getMap();
        //显示定位蓝点
        aMap.getUiSettings().setMyLocationButtonEnabled(false);
        //显示缩放控制器
        aMap.getUiSettings().setZoomControlsEnabled(false);
        //设置弹窗样式
        aMap.setInfoWindowAdapter(new CarMapInfoWindow(_mActivity));
        //marker点击监听
        aMap.setOnMarkerClickListener(this);
        //监听地图移动
        aMap.setOnCameraChangeListener(this);
    }

    private void initPopup() {
        binding.tvFindCarByMapSend.setBackgroundResource(R.drawable.shape_theme_coner);
        TextViewUtils.changeTextView(_mActivity, binding.tvFindCarByMapSend, R.mipmap.ic_down_arrow, true);
        //发货地
        mSendPop = new ThreeLevelAreaWindow(_mActivity) {
            @Override
            protected void resultContent(String name, String simpleName) {
                binding.tvFindCarByMapSend.setText(DefaultUtil.getMaxLengthText(simpleName, 4));
            }
        };
        mSendPop.setAreaSingle();
        mSendPop.setCitySingle();
        mSendPop.setProvinceSingle();
        mSendPop.setShowSimpleName(true);
        mSendPop.setAllSingleSelect(true);
        mSendPop.setOnlyShowProAndCity(true);
        mSendPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                //当选择了发货地后搜索内容要清空
                resetSearchContent();
                viewModel.ldFilter.getValue().setSend(entity);
                if ("不限".equals(entity.getProvinceName())) {
                    //地图缩小展示全中国
                    narrowMapToMin();
                } else {
                    //查找经纬度刷新地图
                    viewModel.getLocation(_mActivity, entity.getCityName(), DefaultUtil.getString(entity.getAreaName()));
                }
            }
        });
        mSendPop.setOnDismissListener(() -> {
            binding.tvFindCarByMapSend.setBackgroundResource(R.drawable.shape_theme_coner);
            TextViewUtils.changeTextView(_mActivity, binding.tvFindCarByMapSend, R.mipmap.ic_down_arrow, true);
        });
        //目的地
        mDestPop = new ThreeLevelAreaWindow(_mActivity) {
            @Override
            protected void resultContent(String name, String simpleName) {
                binding.tvFindCarByMapDest.setText(DefaultUtil.getMaxLengthText(simpleName, 4));
                binding.tvFindCarByMapDest.setBackgroundResource(R.drawable.shape_theme_coner);
            }
        };
        mDestPop.setAreaSingle();
        mDestPop.setCitySingle();
        mDestPop.setProvinceSingle();
        mDestPop.setShowSimpleName(true);
        mDestPop.setAllSingleSelect(true);
        mDestPop.setOnlyShowProAndCity(true);
        mDestPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                //当选择了目的地后搜索内容要清空
                resetSearchContent();
                viewModel.ldFilter.getValue().setDest(entity);
                //刷新
                viewModel.getCarList(_mActivity);
            }
        });
        mDestPop.setOnDismissListener(() -> {
            if ("目的地".equals(binding.tvFindCarByMapDest.getText())) {
                TextViewUtils.changeTextView(_mActivity, binding.tvFindCarByMapDest, R.mipmap.ic_down_arrow_n, false);
            } else {
                TextViewUtils.changeTextView(_mActivity, binding.tvFindCarByMapDest, R.mipmap.ic_down_arrow, true);
            }
        });
        //车长
        mLenPop = new GoodsTypePopWindow3(_mActivity);
        mLenPop.setOnResultClick((key1, key2, key3) -> {
            //当选择了车长后搜索内容要清空
            resetSearchContent();
            GoodsInfoTypeEntity3 entity = (GoodsInfoTypeEntity3) key1;
            binding.tvFindCarByMapType.setText(entity.getName());
            binding.tvFindCarByMapType.setBackgroundResource(R.drawable.shape_theme_coner);
            viewModel.ldFilter.getValue().setCarLen(entity);
            //筛选车长类型时删除所有标注点
            clearMarker();
            //刷新
            viewModel.getCarList(_mActivity);
        });
        mLenPop.setOnDismissListener(() -> {
            if ("车长".equals(binding.tvFindCarByMapType.getText())) {
                TextViewUtils.changeTextView(_mActivity, binding.tvFindCarByMapType, R.mipmap.ic_down_arrow_n, false);
            } else {
                TextViewUtils.changeTextView(_mActivity, binding.tvFindCarByMapType, R.mipmap.ic_down_arrow, true);
            }
        });
        //车辆类型
        mTypePop = new GoodsTypePopWindow3(_mActivity);
        mTypePop.setOnResultClick((key1, key2, key3) -> {
            //当选择了车型后搜索内容要清空
            resetSearchContent();
            GoodsInfoTypeEntity3 entity = (GoodsInfoTypeEntity3) key1;
            viewModel.ldFilter.getValue().setCarType(entity);
            binding.tlFindCarByMap.selectTab(binding.tlFindCarByMap.getTabAt((Integer) key2));
            //根据车型筛选数据
            filterByCarType();
        });
        mTypePop.setOnDismissListener(() -> {
            binding.ivFindCarByMapEdit.setImageResource(R.mipmap.btn_expand1);
        });
        //地图车辆弹窗
        mMapCarPop = new MapCarPopWindow(_mActivity);
        mMapCarPop.setOnDismissListener(this::resetOtherMarker);
    }

    private void narrowMapToMin() {
        //地图缩小展示全中国
        mZoom = mMinZoom;
        mIsNeedLoadByCamera = true;
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mCenterLatLng, mZoom));
    }


    private void initEvent() {
        binding.setOnClick(this);
        //车辆类型数据
        viewModel.ldCarType.observe(this, list -> {
            mTypePop.setData(list, 0);
            //添加tab
            for (GoodsInfoTypeEntity3 entity3 : list) {
                binding.tlFindCarByMap.addTab(binding.tlFindCarByMap.newTab().setText(entity3.getName()));
            }
            //车辆类型选中监听
            binding.tlFindCarByMap.addOnTabSelectedListener(this);
        });
        //车辆长度数据
        viewModel.ldCarLen.observe(this, list -> {
            mLenPop.setData(list, 0);
        });
        //省市区监听
        viewModel.ldAddress.observe(this, addressEntities -> {
            //设置数据

            mDestPop.setData(addressEntities, true);
            mSendPop.setDataAndPosition(addressEntities, "", "", "",
                    true, true);
            mZoom = mMinZoom;
            mIsNeedLoadByCamera = true;
            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mCenterLatLng, mZoom));

            binding.tvFindCarByMapSend.setBackgroundResource(R.drawable.shape_theme_coner);
            TextViewUtils.changeTextView(getActivity(), binding.tvFindCarByMapSend, R.mipmap.ic_down_arrow, true);
            binding.tvFindCarByMapSend.setText("全国");
        });
        //查找地区下标监听
        viewModel.ldPosition.observe(this, positionEntity -> {
            GoodsSourceLocationEntity entity = viewModel.ldFilter.getValue().getSend();
            mSendPop.setDataAndPosition(viewModel.ldAddress.getValue(), entity.getProvinceName(),
                    entity.getCityName(), "", true, true);
            //设置车辆位置
            binding.tvFindCarByMapSend.setText(DefaultUtil.getMaxLengthText(entity.getCityName(), 4));
        });
        //根据省市区查找经纬度监听
        viewModel.ldLatLng.observe(this, latLng -> {
            if (latLng != null) {
                mZoom = 11;
                cameraToPosition(latLng.latitude, latLng.longitude);
                viewModel.getCarList(_mActivity);
            }
        });
        //地图找车数据
        viewModel.ldCars.observe(this, this::refreshMapMarker);
    }

    private void initData() {
        //设置城市
        if (PermissionUtils.checkPermission(_mActivity, Manifest.permission.ACCESS_FINE_LOCATION)) {
            //设置经纬度
            double lat = NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "0"));
            double log = NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "0"));
            if (lat != 0 && log != 0) {
                //设置定位信息
                mCurLatLng = new LatLng(lat, log);
                viewModel.ldFilter.getValue().setLatitude(mCurLatLng.latitude);
                viewModel.ldFilter.getValue().setLongitude(mCurLatLng.longitude);
            }
        }
        //获取数据
        viewModel.getAddressModel(_mActivity);
    }

    /**
     * 清除页面marker
     */
    private void clearMarker() {
        aMap.clear();
        mMarkers.clear();
    }

    /**
     * 刷新地图覆盖物
     */
    private void refreshMapMarker(List<MapCarEntity> list) {
        clearMarker();
        if (list == null || list.size() == 0) return;
        //添加新marker，清空历史marker
        for (MapCarEntity entity : list) {
            addMarker(new LatLng(entity.getLatitude(), entity.getLongitude()), R.mipmap.ic_find_car_marker_yellow, entity);
        }
    }

    /**
     * 添加覆盖物
     */
    private void addMarker(LatLng latLng, @DrawableRes int drawable, MapCarEntity entity) {
        //去重
        for (Marker marker : mMarkers) {
            MapCarEntity oldEntity = (MapCarEntity) marker.getObject();
            //更新marker数据，并返回
            if (oldEntity.getCarrierNo().equals(entity.getCarrierNo())) {
                //判断是否有消息
                if (oldEntity.getImContact() != null) {
                    entity.setImContact(oldEntity.getImContact());
                }
                marker.setObject(entity);
                marker.setPosition(latLng);
                marker.setIcon(BitmapDescriptorFactory.fromResource(drawable));
                return;
            }
        }
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(latLng);
        markerOption.icon(BitmapDescriptorFactory.fromResource(drawable));
        Marker marker = aMap.addMarker(markerOption);
        //设置附着对象
        marker.setObject(entity);
        mMarkers.add(marker);
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        //处于搜索状态的时候重置为选择不限车型，在这里规避根据不限再次发出请求
        if (currentIsSearching) {
            return;
        }
        if (viewModel.ldCarType.getValue() != null && tab.getPosition() < viewModel.ldCarType.getValue().size()) {
            //当切换了车型后后搜索内容要清空
            resetSearchContent();
            mTypePop.setDefItem(tab.getPosition());
            //请求数据
            viewModel.ldFilter.getValue().setCarType(viewModel.ldCarType.getValue().get(tab.getPosition()));
            //根据车型筛选数据
            filterByCarType();
        }
    }

    /**
     * 根据车型筛选数据
     */
    private void filterByCarType() {
        //筛选车长类型时删除所有标注点
        clearMarker();
        //切换车型时重置车长，填充车长筛选数据
        viewModel.ldFilter.getValue().setCarLen(null);
        //刷新车长数据
        if (viewModel.ldFilter.getValue() != null && viewModel.ldFilter.getValue().getCarType() != null) {
            viewModel.ldCarLen.postValue(viewModel.ldFilter.getValue().getCarType().getCarLenList());
        }
        binding.tvFindCarByMapType.setText("车长");
        binding.tvFindCarByMapType.setBackgroundResource(R.drawable.shape_gray_coner);
        TextViewUtils.changeTextView(_mActivity, binding.tvFindCarByMapType, R.mipmap.ic_down_arrow_n, false);
        //刷新
        viewModel.getCarList(_mActivity);
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
        //不用实现
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {
        //不用实现
    }

    /**
     * 根据经纬度移动地图，标记中心点
     */
    private void cameraToPosition(Double lat, Double lng) {
        if (lat == 0 || lng == 0) return;
        //标记不是用户滑动
        mIsNeedLoadByCamera = true;
        //切换地图中心点
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), mZoom));
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        //不用实现
    }

    /**
     * 地图移动完毕
     */
    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        //设置定位信息
        mCurLatLng = cameraPosition.target;
        viewModel.ldFilter.getValue().setLatitude(mCurLatLng.latitude);
        viewModel.ldFilter.getValue().setLongitude(mCurLatLng.longitude);
        //设置当前缩放比例
        viewModel.ldFilter.getValue().setZoom(cameraPosition.zoom);
        //设置当前半径
        setCurrentRadius();
        //重新拉取数据，判断是否需要加载数据
        if (mIsNeedLoadByCamera) {
            mIsNeedLoadByCamera = false;
            viewModel.getCarList(_mActivity);
        }
    }

    /**
     * 设置当前半径
     */
    private void setCurrentRadius() {
        //计算并设置设置当前半径(单位：米)
        if (mScreenHeight == 0) {
            mScreenHeight = ScreenUtil.getDisplayHeight();
        }
        //屏幕高度的一半 * 当前缩放1px代表的米数
        String radius = NumberUtil.trim0(mScreenHeight / 2f * aMap.getScalePerPixel());
        //设置半径
        viewModel.ldFilter.getValue().setRadius(radius);
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        MapCarEntity entity = (MapCarEntity) marker.getObject();
        marker.hideInfoWindow();
        marker.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_find_car_marker_yellow_click
        ));
        mLastMarker = marker;
        //显示弹窗
        mMapCarPop.setData(entity);
        mMapCarPop.showPopwindowBottom(binding.mapFindCarByMap);
        return true;
    }

    /**
     * 还原其他marker
     */
    private void resetOtherMarker() {
        if (mLastMarker != null) {
            MapCarEntity entity = (MapCarEntity) mLastMarker.getObject();
            if (entity == null) {
                mLastMarker = null;
                return;
            }
            mLastMarker.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_find_car_marker_yellow));
            mLastMarker = null;
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_find_car_by_map_edit:
                if (viewModel.ldCarType.getValue() != null) {
                    binding.ivFindCarByMapEdit.setImageResource(R.mipmap.btn_expand_up_gray);
                    mTypePop.showPopwindow(binding.llFindCarByMapCategory, 0, 0);
                }
                break;
            case R.id.tv_find_car_by_map_send:
                if (viewModel.ldAddress.getValue() != null) {
                    TextViewUtils.changeTextView(_mActivity, binding.tvFindCarByMapSend, R.mipmap.ic_up_arrow, true);
                    mSendPop.showPopwindow(binding.rlFindCarByMapSelect, 0, 0);
                }
                break;
            case R.id.tv_find_car_by_map_dest:
                if (viewModel.ldAddress.getValue() != null) {
                    TextViewUtils.changeTextView(_mActivity, binding.tvFindCarByMapDest, R.mipmap.ic_up_arrow, true);
                    mDestPop.showPopwindow(binding.rlFindCarByMapSelect, 0, 0);
                }
                break;
            case R.id.tv_find_car_by_map_type:
                //加载数据后展示车长弹窗
                if (viewModel.ldCarLen.getValue() != null) {
                    TextViewUtils.changeTextView(_mActivity, binding.tvFindCarByMapType, R.mipmap.ic_up_arrow, true);
                    mLenPop.showPopwindow(binding.rlFindCarByMapSelect, 0, 0);
                }
                break;
            case R.id.tv_find_car_by_map_load:
                //加载车辆，手动点击时清空省市区no
                viewModel.ldFilter.getValue().setSend(new GoodsSourceLocationEntity());
                viewModel.getCarList(_mActivity);
                //刷新当前定位点地区信息
                viewModel.getCityByLocation(_mActivity, mCurLatLng.latitude, mCurLatLng.longitude);
                break;
            case R.id.tv_search_car:
                boolean canSearch = !TextUtils.isEmpty(getSearchText());
                if (!canSearch) {
                    MToast.showToast(getContext(), "请输入搜索内容");
                    return;
                }
                currentIsSearching = true;
                closeKeybord();
                viewModel.getSearchCarList(getContext(), getSearchText());
                resetFilterData();
                break;
        }
    }

    private String getSearchText() {
        return binding.tvSearchCar.getText().toString();
    }


    private void resetSearchContent() {
        currentIsSearching = false;
        binding.etView.setText("");
    }

    private void resetFilterData() {
        resetSendLocationData();
        resetPurposeLocationData();
        resetCarType();
        resetCarLen();
    }

    private void resetCarLen() {
        if (mLenPop != null) {
            mLenPop.resetSelectItem();
        }
        viewModel.ldFilter.getValue().setCarLen(null);
    }

    private void resetCarType() {
        if (mTypePop != null) {
            mTypePop.resetSelectItem();
        }
        viewModel.ldFilter.getValue().setCarType(null);
        binding.tlFindCarByMap.selectTab(binding.tlFindCarByMap.getTabAt(0));
    }

    private void resetPurposeLocationData() {
        if (mDestPop != null) {
            mDestPop.resetDataAndUI();
        }
        viewModel.ldFilter.getValue().setDest(new GoodsSourceLocationEntity());
        binding.tvFindCarByMapDest.setText("目的地");
        TextViewUtils.changeTextView(_mActivity, binding.tvFindCarByMapDest, R.mipmap.ic_down_arrow_n, false);
        binding.tvFindCarByMapDest.setBackgroundResource(R.drawable.shape_gray_coner);

    }

    private void resetSendLocationData() {
        if (mSendPop != null) {
            narrowMapToMin();
            binding.tvFindCarByMapSend.setText(DefaultUtil.getMaxLengthText("全国", 2));
        }
        viewModel.ldFilter.getValue().setSend(new GoodsSourceLocationEntity());
    }


    @Override
    public void onResume() {
        super.onResume();
        binding.mapFindCarByMap.onResume();

    }

    @Override
    public void onPause() {
        super.onPause();
        binding.mapFindCarByMap.onPause();
    }

    @Override
    public void onSaveInstanceState(@NotNull Bundle outState) {
        super.onSaveInstanceState(outState);
        binding.mapFindCarByMap.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        binding.mapFindCarByMap.onDestroy();
    }
}
